package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.mall.commons.util.jwt.AESUtil;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.ImageResult;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.KaptchaCodeRequest;
import com.cskaoyan.user.dto.KaptchaCodeResponse;
import com.cskaoyan.user.dto.UserRegisterRequest;
import com.cskaoyan.user.dto.UserRegisterResponse;
import com.cskaoyan.user.service.IKaptchaService;
import com.cskaoyan.user.service.IRegisterService;
import com.cskaoyan.user.utils.VerifyCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.net.URLClassLoader;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class RegisterServiceImpl implements IRegisterService {
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private UserVerifyMapper userVerifyMapper;
    @Autowired
    private JavaMailSender mailSender;

    @Override
    public UserRegisterResponse register(UserRegisterRequest userRegisterRequest) {
        log.info("register方法");
        UserRegisterResponse userRegisterResponse = new UserRegisterResponse();
        //判空验证
        userRegisterRequest.requestCheck();
        //验证用户名是否重复
        volidUserNameRepeat(userRegisterRequest);
        Member member = new Member();
        member.setUsername(userRegisterRequest.getUserName());
        member.setEmail(userRegisterRequest.getEmail());
        AESUtil aesUtil = new AESUtil(userRegisterRequest.getUserPwd());
        member.setPassword(aesUtil.encrypt());
        //   DigestUtils.md5DigestAsHex(userRegisterRequest.getUserPwd().getBytes());
        member.setCreated(new Date());
        member.setUpdated(new Date());
        member.setIsVerified("N");
        member.setState(1);


        int effectRows = memberMapper.insert(member);
        if (effectRows != 1) {
            userRegisterResponse.setCode(UserRetCode.USER_REGISTER_FAILED.getCode());
            userRegisterResponse.setMsg(UserRetCode.USER_REGISTER_FAILED.getMessage());


            return userRegisterResponse;
        }
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(member.getUsername());
        String uuid = UUID.randomUUID().toString();
        userVerify.setUuid(uuid);
        userVerify.setRegisterDate(new Date());
        userVerify.setIsExpire("N");
        userVerify.setIsVerify("N");

        int rows = userVerifyMapper.insert(userVerify);
        if (rows != 1) {
            userRegisterResponse.setCode(UserRetCode.USER_REGISTER_VERIFY_FAILED.getCode());
            userRegisterResponse.setMsg(UserRetCode.USER_REGISTER_VERIFY_FAILED.getMessage());


            return userRegisterResponse;
        }



        //打印日志
        log.info("注册成功,参数request:{}", JSON.toJSONString(userRegisterRequest));
        userRegisterResponse.setCode(UserRetCode.SUCCESS.getCode());
        userRegisterResponse.setMsg(UserRetCode.SUCCESS.getMessage());
        return userRegisterResponse;
    }

    @Override
    @Async
    public void sendEmail(String uuid, UserRegisterRequest userRegisterRequest) {
        log.info("sendEmail");
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject("用户激活项目上见嗷");
        simpleMailMessage.setFrom("1536967974@qq.com");
        simpleMailMessage.setTo(userRegisterRequest.getEmail());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("http://localhost:8099/user/verify?uid=").append(uuid).append("&username=").append(userRegisterRequest.getUserName());
        simpleMailMessage.setText(stringBuilder.toString());
        mailSender.send(simpleMailMessage);


    }

    private void volidUserNameRepeat(UserRegisterRequest userRegisterRequest) {


        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", userRegisterRequest.getUserName());
        List<Member> members = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(members)) {
            throw new ValidateException(UserRetCode.USERNAME_ALREADY_EXISTS.getCode(), UserRetCode.USERNAME_ALREADY_EXISTS.getMessage());
        }

    }
}
